<template>
  <div>
    <div class="app-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        :max-height="200"
        ref="scrollTable"
        @mouseenter.native="autoScroll(true)"
        @mouseleave.native="autoScroll(false)"
      >
        <el-table-column prop="name" align="center" label="姓名"></el-table-column>
        <el-table-column prop="age" align="center" label="年龄"></el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loading: false,
      tableData: [
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 },
        { name: "zhangsan", age: 10 }
      ],
      scrolltimer: "" // 自动滚动的定时任务
    };
  },
  mounted() {
    this.autoScroll();
  },
  beforeDestroy() {
    this.autoScroll(true);
  },
  methods: {
    // 设置自动滚动
    autoScroll(stop) {
      const table = this.$refs.scrollTable;
      // 拿到表格中承载数据的div元素
      const divData = table.$refs.bodyWrapper;
      // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
      if (stop) {
        //再通过事件监听，监听到 组件销毁 后，再执行关闭计时器。
        window.clearInterval(this.scrolltimer);
      } else {
        this.scrolltimer = window.setInterval(() => {
            
          // 元素自增距离顶部1像素
          divData.scrollTop += 2;
          // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
          if (
            divData.clientHeight + divData.scrollTop ==
            divData.scrollHeight
          ) {
            // 重置table距离顶部距离
            divData.scrollTop = 0;
            // 重置table距离顶部距离。值=(滚动到底部时，距离顶部的大小) - 整个高度/2
            // divData.scrollTop = divData.scrollTop - divData.scrollHeight / 2
          }
        }, 150); // 滚动速度
      }
    }
  }
};
</script>
